package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.LanSearchResultAdapter;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.InfoDialog;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.LanSearchUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/7/14.
 */
public class BoxModifyActivity extends BaseActivity implements INetworkInteractUtil {
    private final int EXIT = 2;
    private final int CANCEL = -1;
    private final int ADDBOXBYINPUT = 1;
    private final int ADDBOXBYLANSEARCH = 6;
    private final int MODIFYBOX = 2;
    private final int DELETEBOX = 3;
    private EditText etBoxname;
    private EditText etBoxuid;
    private EditText etBoxpassword;
    private Button btAdd;
    private int flag;
    private NetworkInteractUtil interactUtil;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private BoxBean boxbean;
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (etBoxname.getText().toString().trim().equals("")) {
                showToast(getString(R.string.name_can_not_empty));
                return;
            }
            if (etBoxuid.getText().toString().trim().equals("")) {
                showToast(getString(R.string.uid_can_not_empty));
                return;
            }
            if (etBoxpassword.getText().toString().trim().equals("")) {
                showToast(getString(R.string.password_can_not_empty));
                return;
            }
            if (boxbean == null) {
                boxbean = new BoxBean();
            }
            String title = etBoxname.getText().toString().trim();
            String uid = etBoxuid.getText().toString().trim();
            boxbean.setTitle(title);
            boxbean.setUsername("admin");
            boxbean.setPassword(etBoxpassword.getText().toString().trim());
            boxbean.setUid(etBoxuid.getText().toString().trim());
            if (checkRepeatTitle(title)) {
                showToast(getString(R.string.name_had_used));
                return;
            }
            if (checkRepeatUid(uid)) {
                showToast(getString(R.string.uid_had_been_used));
                return;
            }

            if (flag == ADDBOXBYINPUT || flag == ADDBOXBYLANSEARCH) {
                if (SystemConstant.loginStatus == SystemConstant.Offline) {
//                    showToast(getString(R.string.operate_befor_login));
//                    return;
                    boxbean.setHubId("LOCAL");
                    boxbean.setOwner(SharedUtil.getInstance().readUserId());
                    boxbean.setIsSynced(true);
                    Intent intent = new Intent();
                    intent.putExtra("BoxBean", boxbean);
                    setResult(ADDBOXBYINPUT, intent);
                    mHandler.sendEmptyMessage(EXIT);
                } else if (SystemConstant.loginStatus == SystemConstant.Online) {
                    syncAddBox();
                }
            } else if (flag == MODIFYBOX) {
                Intent intent = new Intent();
                intent.putExtra("position", getIntent().getIntExtra("position", -1));
                intent.putExtra("BoxBean", boxbean);
                syncModifyBox(boxbean);
                setResult(MODIFYBOX, intent);
                showLoadingDialog(BoxModifyActivity.this, getString(R.string.activity_box_modify_syncing));
            }
        }
    };
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setResult(CANCEL);
            finish();
            overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        }
    };
    private ArrayList<String> resultList;
    private MenuItem mProgressMenu;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setLoadingState(true);
                    break;
                case 1:
                    setLoadingState(false);
                    break;
                case EXIT:
                    exit();
                    break;
            }
        }
    };
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_delete:
                    deleteAlert(boxbean.getTitle());
                    break;
                case R.id.action_search:
                    lanSearch();
                    break;
            }
            return true;
        }
    };

    private void assignViews() {
        etBoxname = (EditText) findViewById(R.id.et_username);
        etBoxuid = (EditText) findViewById(R.id.et_boxuid);
        etBoxpassword = (EditText) findViewById(R.id.et_boxpassword);
        btAdd = (Button) findViewById(R.id.bt_add);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boxmodify);
        assignViews();
        interactUtil = new NetworkInteractUtil(this);
        flag = getIntent().getIntExtra("flag", -1);
        setBar(flag);
        setData(flag);
        switchMode();
    }

    private void switchMode() {
        if (flag == 6) {
            showLoadingDialog(this, getString(R.string.searching));
            lanSearch();
        }
    }

    private void setBar(int flag) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        if (flag == ADDBOXBYINPUT) {
            //添加Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_boxmodify_add));
        } else if (flag == MODIFYBOX) {
            //修改Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_boxmodify_modify));
        } else {
            //添加Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_boxmodify_add));
        }
        setSupportActionBar(toolbar);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(CANCEL);
                finish();
                overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            }
        });
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void setData(int flag) {
        if (flag == ADDBOXBYINPUT) {
            //添加Box
            String uid = getIntent().getStringExtra("uid");
            if (!TextUtils.isEmpty(uid)) {
                etBoxuid.setText(uid);
            }
            btAdd.setText(getString(R.string.save));
        } else if (flag == MODIFYBOX) {
            //修改Box
            Intent intent = getIntent();
            boxbean = intent.getParcelableExtra("BoxBean");
            etBoxname.setText(boxbean.getTitle());
            etBoxuid.setText(boxbean.getUid());
            etBoxpassword.setText(boxbean.getPassword());
            btAdd.setText(getString(R.string.save));
        } else {
            //添加Box
            String uid = getIntent().getStringExtra("uid");
            if (!TextUtils.isEmpty(uid)) {
                etBoxuid.setText(uid);
            }
            btAdd.setText(getString(R.string.save));
        }
        btAdd.setOnClickListener(mBtnOnClickListener);
    }

    private boolean checkRepeatUid(String uid) {
        if (flag == ADDBOXBYINPUT) {
            for (BoxBean box : SystemConstant.boxBeanList) {
                if (uid.equals(box.getUid())) {
                    return true;
                }
            }
        } else if (flag == MODIFYBOX) {
            int position = getIntent().getIntExtra("position", -1);
            for (int i = 0; i < SystemConstant.boxBeanList.size(); i++) {
                if (uid.equals(SystemConstant.boxBeanList.get(i).getUid())) {
                    if (i == position) {
                        continue;
                    } else {
                        return true;
                    }
                }
            }
        } else if (flag == ADDBOXBYLANSEARCH) {
            for (BoxBean box : SystemConstant.boxBeanList) {
                if (uid.equals(box.getUid())) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean checkRepeatTitle(String title) {
        if (flag == ADDBOXBYINPUT) {
            for (BoxBean box : SystemConstant.boxBeanList) {
                if (title.equals(box.getTitle())) {
                    return true;
                }
            }
        } else if (flag == MODIFYBOX) {
            int position = getIntent().getIntExtra("position", -1);
            for (int i = 0; i < SystemConstant.boxBeanList.size(); i++) {
                if (title.equals(SystemConstant.boxBeanList.get(i).getTitle())) {
                    if (i == position) {
                        continue;
                    } else {
                        return true;
                    }
                }
            }
        } else if (flag == ADDBOXBYLANSEARCH) {
            for (BoxBean box : SystemConstant.boxBeanList) {
                if (title.equals(box.getTitle())) {
                    return true;
                }
            }
        }
        return false;
    }

    private void syncAddBox() {
        System.out.println("BoxModifyActivity syncAddBox");
        if (boxbean.isSynced()) {
            return;
        }
        JSONObject jsonParam = new JSONObject();
        JSONObject jsonDevice = new JSONObject();
        try {
            jsonDevice.put("did", boxbean.getUid());
            jsonDevice.put("username", boxbean.getUsername());
            jsonDevice.put("password", boxbean.getPassword());
            jsonDevice.put("alias", boxbean.getTitle());
            jsonParam.put("device", jsonDevice);

            JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
            jsonParam.put("username", loginSp.getString("username"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        interactUtil.syncAddBox(jsonParam);
    }

    private void lanSearch() {
        mHandler.sendEmptyMessage(0);
        LanSearchUtil.getInstance().search(BoxModifyActivity.this, new LanSearchUtil.SearchResultInterface() {
            @Override
            public void onResultCallBack(int ret, Object object) {
                resultList = (ArrayList<String>) object;
                mHandler.sendEmptyMessage(1);
            }

            @Override
            public void onResultIPCallBack(String uid, String ip) {
            }
        });
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    public void setLoadingState(boolean refreshing) {
        if (mProgressMenu != null) {
            if (refreshing) {
                mProgressMenu.setActionView(R.layout.actionbar_indeterminate_progress);
                mProgressMenu.setVisible(true);
                showLoadingDialog(BoxModifyActivity.this, getString(R.string.searching));
            } else {
//                mProgressMenu.setVisible(false);
                mProgressMenu.setActionView(null);
                hideLoadingDialog();
                showSearchResultDialog();
            }
        } else {
        }
    }

    private void showSearchResultDialog() {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(BoxModifyActivity.this);
        customsizeDialog.setTitle(getString(R.string.dialog_title_search_result));
        customsizeDialog.setListviewAdapter(new LanSearchResultAdapter(this, resultList));
        customsizeDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (resultList.size() != 0)
                    etBoxuid.setText(resultList.get(customsizeDialog.getChoosenPosition()));
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar_modify_box, menu);
        mProgressMenu = menu.findItem(R.id.action_search);
        if (flag == ADDBOXBYINPUT) {
            menu.findItem(R.id.action_delete).setVisible(false);
        } else if (flag == MODIFYBOX) {
            menu.findItem(R.id.action_search).setVisible(false);
        } else if (flag == ADDBOXBYLANSEARCH) {
            menu.findItem(R.id.action_delete).setVisible(false);
            mProgressMenu.setActionView(R.layout.actionbar_indeterminate_progress);
            mProgressMenu.setVisible(true);
        }
        return true;
    }

    /**
     * 删除提示
     */
    private void deleteAlert(String itemname) {
        final InfoDialog delateAlertDialog = new InfoDialog(BoxModifyActivity.this);
        delateAlertDialog.setTitle(getString(R.string.dialog_title_alert));
        delateAlertDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure), itemname));
        delateAlertDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delateAlertDialog.dismiss();
            }
        });
        delateAlertDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delateAlertDialog.dismiss();
                syncRemoveBox();
                showLoadingDialog(BoxModifyActivity.this, getString(R.string.activity_box_modify_deleting));
            }
        });
        delateAlertDialog.show();
    }


    private void removeBox() {
        Intent intent = new Intent();
        intent.putExtra("position", getIntent().getIntExtra("position", -1));
        setResult(DELETEBOX, intent);
        finish();
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
    }

    private void syncRemoveBox() {
        JSONObject jsonPost = new JSONObject();
        interactUtil.syncRemoveBox(boxbean.getHubId(), jsonPost);
    }

    private void syncModifyBox(BoxBean boxBean) {
        if (boxBean.isSynced()) {
            interactUtil.syncModifyBox(boxBean.getUid(), boxBean.getModifyInfo());
            return;
        }
        finish();
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(interactUtil.SYNCMODIFYBOX)) {
            if (ret == 0) {
                hideLoadingDialog();
                finish();
                overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            } else if (ret == -1) {
                hideLoadingDialog();
                showToast(getString(R.string.activity_box_modify_modify_failed));
            }
        } else if (flag.equals(interactUtil.SYNCREMOVEBOX)) {
            if (ret == 0) {
                hideLoadingDialog();
                removeBox();
            } else if (ret == -1) {
                hideLoadingDialog();
                showToast(getString(R.string.activity_box_modify_delete_failed));
            }
        } else if (flag.equals(interactUtil.SYNCADDBOX)) {

            System.out.println("NetworkInteractUtil syncAddBox has onNetworkInteractOver, ret = " + ret);

            if (ret == 0) {
                JSONObject response = (JSONObject) object;


                int code = -1;
                String hubId = null;
                try {
                    System.out.println("NetworkInteractUtil syncAddBox has onNetworkInteractOver, response = " + response.toString(2));
                    code = response.getInt("code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                System.out.println("NetworkInteractUtil syncAddBox has onNetworkInteractOver, code = " + code);

                try {
                    if (code == 0) {
                        //操作成功
                        hubId = response.getString("id");
                        boxbean.setHubId(hubId);
                        boxbean.setOwner(SharedUtil.getInstance().readUserId());
                        boxbean.setIsSynced(true);
                        Intent intent = new Intent();
                        intent.putExtra("BoxBean", boxbean);
                        setResult(ADDBOXBYINPUT, intent);
                        mHandler.sendEmptyMessage(EXIT);
                    } else {
                        showToast(getString(R.string.box_has_added));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (ret == -1) {
                hideLoadingDialog();
                showToast(getString(R.string.box_add_failed));
            }
        }
    }


}
